﻿using System;
using System.Configuration;
using Citi.Helpers;
using Citi.RoutineBase;
using System.IO;

namespace Citi.PTSConsolidation.ConsoleUI.ClientExtraction
{
    class Program
    {
        private static string ExcelClientAllocation { get { return ConfigurationManager.AppSettings["ExcelClientAllocation"]; } }
        private static string ExecutionLog { get { return ConfigurationManager.AppSettings["ExecutionLog"]; } }

        static void Main(string[] args)
        {
            if (File.Exists(ExecutionLog))
                File.Delete(ExecutionLog);

            var action = new CurrentAction();
            var writer = new ConsoleInFile(ExecutionLog);
            Console.SetOut(writer);

            RefreshPivots(DateTime.Today.Year, action);
            //RefreshPivots(DateTime.Today.AddYears(-1).Year, action);
            //RefreshPivots(DateTime.Today.AddYears(1).Year, action);
        }

        static void RefreshPivots(int year, CurrentAction action)
        {
            try
            {
                var excelFile = string.Format(ExcelClientAllocation, year);

                Console.WriteLine("Refreshing file {0}", excelFile);

                if (!File.Exists(excelFile))
                {
                    Console.WriteLine("File was not found");
                    return;
                }

                var excelTemp = string.Format(@"C:\Temp\{0}", Path.GetFileName(excelFile));

                Console.WriteLine("Copying file local");
                File.Copy(excelFile, excelTemp, true);

                new Helpers.ExcelHelper().RefreshAll(excelTemp);
                Console.WriteLine("Pivots are refreshed");

                File.Copy(excelTemp, excelFile, true);
                Console.WriteLine("File copied to PTS Folder");
            }
            catch (Exception e)
            {
                Console.WriteLine("Pivots are NOT refreshed. {0}", e.Message);
            }
        }
    }
}
